<template>
  <div class="main">
    <SearchHeader @searchBook="searchBook"></SearchHeader>
    <div class="con">
      <template v-if="books.length > 0 ">
        <van-grid :column-num="3" :border="false">
          <van-grid-item class="item" v-for="(book,index) in books" :key="'b'+index"  @click="goBookDetail(book)">
            <div class="cover">
              <img :src="book.cover" alt="book.name" srcset="">
            </div>
            <div class="name">{{book.name}}</div>
            <div class="author">{{book.author}}</div>
          </van-grid-item>
        </van-grid>
      </template>
      <div v-if="bookName && books.length ===0" class="c-tip">
        <div>暂无搜索结果</div>
      </div>
    </div>
  </div>
</template>
<script>
import SearchHeader from '@/components/SearchHeader'
export default {
  name:'Category',
  components:{
    SearchHeader,
  },
  async asyncData(ctx) {
    try{
      let bookName = ctx.query.bookName && encodeURIComponent(ctx.query.bookName) || ''
      let books = []
      if(bookName){
        books =await ctx.$axios.get('/api/getBooksByName?bookName=' + bookName+'&isShow=1&status=1')
      }
      return {
        bookName,
        books
      }
    }catch(err){
      console.log('error:',err)
      ctx.$errorHandler(err)
    }
  },
  data(){
    return {
      bookName: this.$route.query.bookName,
      books:[]
    }
  },

  methods: {
    async searchBook(bookName){
      if(bookName){
        this.bookName = bookName
        this.books = await this.$axios.get('/api/getBooksByName?bookName=' + bookName+'&isShow=1&status=1') 
      }
      // console.log('this.books:',this.books);
    },
    goBookDetail(book){
      this.$router.push({path : '/book', query:{bookId: book.id}})
    }
  },
}
</script>
<style lang="scss" scoped>
.main{
  .con{
    margin: auto;
    .item{
      margin-bottom: 10px;
      text-align: left;
      .cover{
        width: 100px;
        height: 130px;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .name{
        font-size: 14px;
      }
      .author{
        font-size: 14px;
        color:#aba59a;
      }
    }
    .c-tip{
      font-size: 14px;
      text-align: center;
      width: 100%;
      margin-top: 30px;
      color: #ddd;
    }
  }
}
</style>